//
//  YbrDlnaPlayer.m
//  wifibox
//
//  Created by os X 10.9 on 15-1-14.
//  Copyright (c) 2015年 yinbaner. All rights reserved.
//  dlna的播放器类



#define QuickScanTimeSpace       2      // 2s - 快速扫描的时候的时间间隔
#define SlowScanTimeSpace        4      // 4s - 慢速扫描的时间间隔


#import "YbrDlnaPlayer.h"
#import "YbrMusicItem.h"
#import <MediaPlayer/MediaPlayer.h>
#import "YbrNoTimeList.h"
#import "YbrDlnaClassItem.h"
#import "YbrDlnaMusic.h"
#import "YbrDlnaMyTime.h"
#import "YbrSetUpBaseReq.h"
#import "YbrDevice.h"
#import "YbrSetUpWifiBoxUtil.h"
#import "YbrDlnaTempPlaylistDao.h"
#import "MKNetworkEngine.h"
#import "YbrJsonUtil.h"
#import "YbrTimerUtil.h"
#import "YbrDLNAUtil.h"
#import "YbrFileUtils.h"
#import "IWHttpTool.h"
#import "YbrSandBox.h"
#import "NSString+Ybr.h"
#import "YbrHTTPServiceUtil.h"
#import "YbrMusicPlayUtil.h"

@interface YbrDlnaPlayer () {
    int             playPos;            // 正在播放的是哪一个
    int             playLen;            // 播放的list的长度
    int             seek;               // 播放的进度条
    int             volume;             // 播放的声音大小
    YbrMusicItem    * musicItem;        // 正在播放的类
    BOOL            isPlaying;          // 是否正在播放
    NSArray         * musiclist;        // 播放的列表
    NSString        * lastListID;       // 上次发送歌曲的时候连接的ID
    
    // 下面的是DeviceInfo
    NSString        * playListUrl;      // 正在播放的列表的Url
    NSString        * currUrl;          // 正在播放的歌曲的url
    NSString        * currentState;        // 现在的播放状态
    NSString        * currDuration;     // 这个歌曲的CurrDuration
    int             currentTimePos;     // 歌曲当前播放的时间位置
    //NSString        * timePosition;     // 当前歌曲进行到哪里了
    NSString        * currMusicStr;     // 当前播放歌曲的Item
    int             currVolume;         // 当前的音量
    NSTimer         * timer;
    BOOL            isGetInfoRun;
    
    int             removeNum;          // 要移除的消息()
    BOOL            isTime;             // 是否是定时
    NSString        * timeID;           // 整个定时的ID
    NSString        * playTimeID;       // 现在正在播放的定时的列表的ID
    // 记录定时器的时间
    int             timerSecondCount;   // 记录定时器的计数器
    
    // 记录获取音箱信息的请求错误次数
    int             httpDeviceInfoErrorCount;  // 计算获取音箱信息错误的次数
    // 是否慢速扫描
    BOOL            isSlow;             // 是否慢速扫描
    NSString *currListID;
    NSString *timePosition;
}
@end


@implementation YbrDlnaPlayer

+(YbrDlnaPlayer *) getInstance
{
    return [[self alloc] init];
}


-(id)init
{
    self                =   [super init];
    playPos             =   -1;
    playLen             =   -1;
    isGetInfoRun        =   NO;
    timerSecondCount    =   0;
    currentTimePos      =   0; // 当前播放的时间点(秒为计算)
    httpDeviceInfoErrorCount = 0; // 当前获取音箱信息错误的次数为0
    isSlow              =   NO;
    
    return self;
}

// 播放音频
-(void) playAll:(NSArray *) mymusiclist position:(int) position
{
    if(mymusiclist == nil || mymusiclist.count == 0)
    {
        return;
    }
    
    // 在这个之前要将文件保存到本地才行
    // 判断音箱上面的播放列表的ID发生改变了没有,如果没有则直接执行跳转命令就行了
    if([lastListID isEqualToString:currListID])
    {
        BOOL flag = NO; // 有没有不相同的
        for (int i = 0; i < mymusiclist.count; i ++)
        {
            YbrMusicItem *tempMusicItem = mymusiclist[i];
            
            if(![self posIsEqu:i ID:[NSString stringWithFormat:@"%i" ,tempMusicItem.musicId]])
            {
                flag = YES;
                break;
            }
            // 超过50个就相当于相同了
            if(i == 50)
            {
                break;
            }
        }
        // 表明列表是同一个列表
        if(!flag && mymusiclist.count == musiclist.count)
        {
            [self setQueuePosition:position + 1];
            return;
        }
    }
    
    // 将其保存到dlna的临时列表当中
    YbrDlnaTempPlaylistDao *dlnaTempPlay        =   [[YbrDlnaTempPlaylistDao alloc] init];
    [dlnaTempPlay setTemplistByArr:mymusiclist];
    
    // 下面将播放列表保存到本地
    YbrNoTimeList *noTimeList                   =   [[YbrNoTimeList alloc] init];
    noTimeList.FileType                         =   NoTimeType;
    
    NSMutableArray *dlnaClassItemArr            =   [NSMutableArray array];
    YbrDlnaClassItem *dlnaClassItem             =   [[YbrDlnaClassItem alloc] init];
    
    NSMutableArray *dlnamusics                  =   [NSMutableArray array];
    YbrDlnaMusic *dlnaMusic                     =   nil;
    
    musiclist                                   =   mymusiclist;
    
    for (int i = 0; i < mymusiclist.count; i ++)
    {
        YbrMusicItem *tempMusicItem             =   mymusiclist[i];
//        dlnaMusic                               =   [YbrDlnaMusic musicItemToDlnaMusic:tempMusicItem position:i];
        [dlnamusics addObject:dlnaMusic];
    }
    lastListID                  =   [NSString stringWithFormat:@"%i" ,(int)[[NSDate date] timeIntervalSince1970]];
    dlnaClassItem.id            =   lastListID;
    dlnaClassItem.musics        =   dlnamusics;
    dlnaClassItem.module        =   PlayModeCycle;
    dlnaClassItem.begin         =   [NSString stringWithFormat:@"%i" ,position];
    
    [dlnaClassItemArr addObject:dlnaClassItem];
    noTimeList.classItems       =   dlnaClassItemArr;
    NSString *content           =   [YbrJsonUtil getJson:noTimeList];
    
    // 将列表的信息保存到本地
    [YbrFileUtils saveStrForFile:NoTimerPath content:content];
    
    
    NSLog(@"----播放列表内容-------------%@",content);
    
    
    
    [self PsuhPlayUrl:[YbrHTTPServiceUtil getHttpPath:NoTimerPath]];
}


// 第几个位置是否相等
-(BOOL) posIsEqu:(int) position ID:(NSString *) ID {
    if(musiclist != nil && musiclist.count > position) {
        NSString *posId = [NSString stringWithFormat:@"%i" ,((YbrMusicItem *) musiclist[position]).musicId];
        if([ID isEqualToString:posId]) {
            return YES;
        }
    }
    return NO;
}


// 推送播放的url
-(void) PsuhPlayUrl:(NSString *) url {
    NSLog(@"推送的地址 --- %@ " ,url);
    NSDictionary * params2              =   [NSDictionary dictionaryWithObjectsAndKeys:url, @"AVTransportURI", nil];
    YbrSetUpBaseReq * setupBaseReq      =   [YbrSetUpBaseReq InitBaseReq:@"SetAVTransportURI" body:params2];
    // 开始网络请求
    NSMutableDictionary * params        =   [NSMutableDictionary dictionary];
    params[@"CMD"]                      =   @"HTTPAPI";
    NSString * req                      =   [YbrJsonUtil getJson:setupBaseReq];
    params[@"JSONREQ"]                  =   req;
    
    [IWHttpTool postWithURL:[[YbrDLNAUtil getInstance] getDeviceReqHttpUrl]  params:params success:^(id json) {
        if([YbrSetUpWifiBoxUtil isOK:json]) {
            // 推送成功,开启获取信息定时器
            timerSecondCount            =   0;
            isSlow                      =   NO;
            [self startGetInfo];
            NSLog(@"推送成功");
            
//            [[NSNotificationCenter defaultCenter] postNotificationName:PUSH_TIMER_LIST_STATUS object:@"success"];
        }else {
            // 判断推送失败的原因
//            [[NSNotificationCenter defaultCenter] postNotificationName:PUSH_TIMER_LIST_STATUS object:@"fail"];
        }
    } failure:^(NSError *error) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:PUSH_TIMER_LIST_STATUS object:@"fail"];
        httpDeviceInfoErrorCount ++;
    }];
}


// 获取设备当前的播放状态+音频信息+播放列表信息
// 隔3s搞它一次
-(void) getDeviceDlnaPlayInfo {
    if(isGetInfoRun == YES) {
        return;
    }
    
    
//    NSLog(@"--测试观察获取设备的状态----getDeviceDlnaPlayInfo----------%d------%@------%@",timerSecondCount,currentState,timePosition);
    
    
    if(timerSecondCount % (isSlow ? 8 : 1) == 0){
        isGetInfoRun            =   YES;
        
        NSDictionary *params2           =   [NSDictionary dictionaryWithObjectsAndKeys:
                                            @"AVTransportURI TransportState CurrentTrackURI CurrentTrackDuration RelativeTimePosition CurrentTrackMetaData CurrentTrack CurrentVolume",@"Variables", nil];
        YbrSetUpBaseReq *setupBaseReq   =   [YbrSetUpBaseReq InitBaseReq:@"GetPlayerState" body:params2];
        // 开始网络请求
        NSMutableDictionary *params     =   [NSMutableDictionary dictionary];
        params[@"CMD"]                  =   @"HTTPAPI";
        NSString *req                   =   [YbrJsonUtil getJson:setupBaseReq];
        params[@"JSONREQ"]              =   req;
        
        [IWHttpTool postWithURL:[[YbrDLNAUtil getInstance] getDeviceReqHttpUrl] params:params success:^(id json) {
            isGetInfoRun                =   NO;
            
//            NSLog(@"查看DeviceInfo的信息  ===   %@" ,json);
            
            if([YbrSetUpWifiBoxUtil isOK:json]) {
                id Body                 =   json[@"Body"];
                
                playListUrl             =   Body[@"AVTransportURI"];
                // 检测是否有变化了
                [self checkPlayListUrlIsChange:playListUrl];
                currUrl                 =   Body[@"CurrentTrackURI"];
                
                if(![currentState isEqualToString:Body[@"TransportState"]]) {
                    currentState           =   Body[@"TransportState"];
                    // 发送状态改变的
                    [self setPlayStateChange];
                }
                
                currentState               =   Body[@"TransportState"];
                
                if ([currentState isEqualToString:@"NO_MEDIA_PRESENT"]) {
                     NSLog(@"----his grandmother---  %@  ----- ", @"is a string");
                }
                
                currDuration            =   Body[@"CurrentTrackDuration"];  // 总时间长度
                timePosition            =   Body[@"RelativeTimePosition"];  // 相对时间长度
                currMusicStr            =   Body[@"CurrentTrackMetaData"];
                playPos                 =   [Body[@"CurrentTrack"] intValue];
                
                if(currVolume != [Body[@"CurrentVolume"] intValue]){
                    currVolume          =   [Body[@"CurrentVolume"] intValue];
                    [MPMusicPlayerController applicationMusicPlayer].volume     =   [self getVolum];
                }
                
                
                
                // 将MusicStr转化出来
                if(currMusicStr != nil) {
                    NSData *data                =   [currMusicStr dataUsingEncoding:NSUTF8StringEncoding];
                    NSError *error;
                    NSDictionary *musicJson     =   [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
                    YbrMusicItem *tempMusicItem =   [[YbrMusicItem alloc] init];
                    id musicId                  =   [musicJson objectForKey:@"id"];
                    tempMusicItem.musicId       =   musicId == nil ? -1 : [musicId intValue];
                    tempMusicItem.musicName     =   [musicJson objectForKey:@"name"];
                    tempMusicItem.singername    =   [musicJson objectForKey:@"singerName"];
                    tempMusicItem.albumname     =   [musicJson objectForKey:@"albumName"];
                    tempMusicItem.downloadurl   =   [musicJson objectForKey:@"url"];
                    tempMusicItem.img           =   [musicJson objectForKey:@"img"];
                    if(musicItem != nil && (tempMusicItem.musicId != musicItem.musicId || ![tempMusicItem.musicName isEqualToString:musicItem.musicName])) {
                        // 要发送改变的了
                        musicItem               =   tempMusicItem;
                        
                        [self setMetaChange];
                    }else {
                        musicItem = tempMusicItem;
                    }
                }
                
                currentTimePos  =   (int)[YbrTimerUtil makeTimeInt:timePosition] + 1;
                
                if (currentTimePos <= 3)
                {
                    isSlow = NO;
                }
                else
                {
                    isSlow = YES;
                }
            }
        } failure:^(NSError *error) {
            isGetInfoRun = NO;
            httpDeviceInfoErrorCount++;
        }];
        
    }
    else
    {
        //播放时间自家
        if([self isPlaying])
        {
            currentTimePos  =   (int)[YbrTimerUtil makeTimeInt:timePosition] + 1;
            timePosition    =   [YbrTimerUtil makeTimeStr:currentTimePos];
            
            if (currentTimePos <= 3)
            {
                isSlow = NO;
            }
            else
            {
               isSlow = YES;
            }
        }
    }
    timerSecondCount ++;
}


#pragma mark 检测播放列表是否发生改变
// 检测播放列表是否发生改变
-(void) checkPlayListUrlIsChange:(NSString *) url {
    
    if([NSString isEmpty:url]) {
        return;
    }
    
    NSArray * content = [url componentsSeparatedByString:@";"];
    
    if(content == nil || (content.count != 2 && content.count != 3)) {
        if([self isPlaying]) {
            removeNum ++;
            if(removeNum == 2) {
                removeNum           =   0;
                timer               =   nil;
                currentState           =   @"STOPPED";
                
                [[YbrDLNAUtil getInstance] setSelectedDevice:nil];
                
                UIAlertView *alert  =   [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备被其他播放器占用" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
                
                [YbrFileUtils deleFile:NoTimerPath];
                [YbrFileUtils deleFile:TimeBoxPath];
                [self sendDlnaPlayChange];
            }
        }
    }
    
    NSString * playlistUri;
    YbrDevice *device               =   [[YbrDLNAUtil getInstance] getSelectedDevice];
    //if(device != nil)
    //{
    playlistUri                 =   [NSString stringWithFormat:@"%@%@" , @"http://" ,device.DeviceIpAddr];
    //}
    
    if([NSString isEmpty:playlistUri]) {
        return;
    }
    
    // 非定时列表
    if(content.count == 2) {
        if([currListID isEqualToString:[NSString stringWithFormat:@"%@",content[1]]]) {
            return;
        } else {
            isTime = NO;
            currListID = content[1];
            
            MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
            
            NSString *requstUrl = [NSString stringWithFormat:@"%@/%@", playlistUri ,@"playlist.html?type=0"];
            
            NSLog(@"要访问的音频的地址是   %@" ,requstUrl);
            
            MKNetworkOperation *op = [engine operationWithURLString:requstUrl params:nil httpMethod:@"GET"];
            [op onCompletion:^(MKNetworkOperation *operation) {
                NSString *result = [op responseString];
                [YbrFileUtils saveStrForFile:NoTimerPath content:result];
                [self sendDlnaPlayChange];
            } onError:^(NSError *error) {
                
            }];
            [engine enqueueOperation:op];            
        }
    } else if(content.count == 3) { // 定时列表
        timeID = content[1];
        playTimeID = content[2];
        if([currListID isEqualToString:content[2]]) {
            return;
        } else {
            isTime = YES;
            currListID = content[2];
            
            MKNetworkEngine *engine = [[MKNetworkEngine alloc] init];
            MKNetworkOperation *op = [engine operationWithURLString:[NSString stringWithFormat:@"%@/%@", playlistUri ,@"playlist.html?type=2"] params:nil httpMethod:@"GET"];
            [op onCompletion:^(MKNetworkOperation *operation) {
                NSString *result = [op responseString];
                [YbrFileUtils saveStrForFile:TimeBoxPath content:result];
                isTime = YES;
                [self sendDlnaPlayChange];
            } onError:^(NSError *error) {
                
            }];
            [engine enqueueOperation:op];
        }
    }
    [self sendDlnaPlayChange];
}


// 发送dlna列表发生变化
#pragma mark 发送dlna列表发生变化
-(void) sendDlnaPlayChange {
    [[NSNotificationCenter defaultCenter] postNotificationName:PlayListChange object:nil];
}


// 停止获取音箱的信息+播放状态
-(void) stopGetInfo {
    if(timer != nil) {
        [timer invalidate];
        timer = nil;
        currListID = @"";
        musiclist = nil;
    }
}


// 开始获取音箱上音频播放的详细信息
// 播放列表,播放时间,音频的详细信息...
-(void) startGetInfo {
    [timer invalidate];
    timer           =   nil;
    isGetInfoRun    =   NO;
    timerSecondCount=   0;
    isSlow          =   NO;
    timer           =   [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getDeviceDlnaPlayInfo) userInfo:nil repeats:YES];
}


// 判断返回的列表跟当前的列表是否一致
-(BOOL)isAlike:(NSArray *)musiclist
{
    // add code here
    return YES;
}


// 返回Arr : YbrMusicItem 正在播放的Item
-(YbrMusicItem *) getQueueItem {
    return musicItem;
}


-(NSString *) getArtistName {
    if(musicItem != nil) {
        NSString *album = musicItem.albumname;
        return [NSString isEmpty:album] ? @"未知专辑" : album;
    }
    return @"未知专辑";
}


-(NSString *) getSingerName {
    if(musicItem != nil) {
        NSString *singer = musicItem.singername;
        return [NSString isEmpty:singer] ? @"未知歌手" : singer;
    }
    return @"未知歌手";
}


-(NSString *) getMusicName {
    if(musicItem != nil) {
        NSString *musicName = musicItem.musicName;
        return [NSString isEmpty:musicName] ? @"未知歌曲" : musicName;
    }
    return @"未知歌曲";
}


// 获取歌曲的时间长度
-(int) getDuration {
    if(![NSString isEmpty:currDuration]) {
        return (int)[YbrTimerUtil makeTimeInt:currDuration];
    }
    return 0;
}


// 获取歌曲的时间位置
-(int) getPoisiton {
    if(![NSString isEmpty:timePosition]) {
        return (int)[YbrTimerUtil makeTimeInt:timePosition];
    }
    return 0;
}


// 获取图片路径
-(NSString *) getBitmap {
    if(musicItem != nil) {
        NSString *img = musicItem.img;
        return img;
    }
    return nil;
}


// 正在播放的音频的ID
-(int) getAudioId {
    if(musicItem != nil)
    {
        int musicId = musicItem.musicId;
        return musicId;
    }
    return -1;
}


// 是否正在播放
-(BOOL) isPlaying
{
    if([currentState isEqualToString:@"STOPPED"]
       ||
       [currentState isEqualToString:@"PAUSED_PLAYBACK"] || [currentState isEqualToString:@"TRANSITIONING"]
       || [currentState isEqualToString:@"PAUSED_RECORDING"] || [currentState isEqualToString:@"RECORDING"]
       || [currentState isEqualToString:@"NO_MEDIA_PRESENT"] ||
       [NSString isEmpty:currentState]
       ) {
        return NO;
    }
    return YES;
}


// 设置队列的位置
-(void) setQueuePosition:(int) index {
    NSDictionary *params2           =   [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%i" ,index], @"Target", @"TRACK_NR" ,@"Unit", nil];
    YbrSetUpBaseReq *setupBaseReq   =   [YbrSetUpBaseReq InitBaseReq:@"PlayerDoSeek" body:params2];
    // 开始网络请求
    NSMutableDictionary *params     =   [NSMutableDictionary dictionary];
    params[@"CMD"]                  =   @"HTTPAPI";
    NSString *req                   =   [YbrJsonUtil getJson:setupBaseReq];
    params[@"JSONREQ"]              =   req;
    
    [IWHttpTool postWithURL:[[YbrDLNAUtil getInstance] getDeviceReqHttpUrl] params:params success:^(id json) {
        NSLog(@"跳转某一条成功");
        //timePosition = @"00:00";
        timerSecondCount            =   0;
        isSlow                      =   NO;
        
        [self getDeviceDlnaPlayInfo];
    } failure:^(NSError *error) {
        NSLog(@"跳转某一条失败");
        httpDeviceInfoErrorCount ++;
    }];
}


// 获取队列的位置
-(int) getQueuePosition {
    return playPos;
}


// 下一曲
-(void) Next {
    [self setQueuePosition:[self getQueuePosition] + 1];
}


// 上一曲
-(void) Prev {
    [self setQueuePosition:[self getQueuePosition] - 1];
}


// 播放或停止
-(void) PlayOrPause {
    if([self isPlaying]) {
        [self stop];
    }else {
        [self play];
    }
}
// 播放
-(void) Play {
    if (![self isPlaying]) {
       [self play];
    }
    
}

// 播放
-(void) play {
    YbrSetUpBaseReq *setupBaseReq   =   [YbrSetUpBaseReq InitBaseReq:@"PlayerDoPlay" body:nil];
    // 开始网络请求
    NSMutableDictionary *params     =   [NSMutableDictionary dictionary];
    params[@"CMD"]                  =   @"HTTPAPI";
    NSString *req                   =   [YbrJsonUtil getJson:setupBaseReq];
    params[@"JSONREQ"]              =   req;
    
    [IWHttpTool postWithURL:[[YbrDLNAUtil getInstance] getDeviceReqHttpUrl] params:params success:^(id json) {
        NSLog(@"播放-----------------播放歌曲成功");
        //重置计算器参数
        timerSecondCount            =   0;
        isSlow                      =   NO;
        [self getDeviceDlnaPlayInfo];
    } failure:^(NSError *error) {
        NSLog(@"播放-----------------播放歌曲失败");
        timerSecondCount            =   0;
        isSlow                      =   NO;
        httpDeviceInfoErrorCount ++;
        [self getDeviceDlnaPlayInfo];
    }];
    
    
}


// 这里暂时和Pause一样
-(void) stop {
    YbrSetUpBaseReq *setupBaseReq   =   [YbrSetUpBaseReq InitBaseReq:@"PlayerDoPause" body:nil];
    // 开始网络请求
    NSMutableDictionary *params     =   [NSMutableDictionary dictionary];
    params[@"CMD"]                  =   @"HTTPAPI";
    NSString *req                   =   [YbrJsonUtil getJson:setupBaseReq];
    params[@"JSONREQ"]              =   req;
    
    [IWHttpTool postWithURL:[[YbrDLNAUtil getInstance] getDeviceReqHttpUrl] params:params success:^(id json) {
        NSLog(@"播放-----------------暂停歌曲成功");
        //重置参数
        timerSecondCount            =   0;
        isSlow                      =   NO;
        [self getDeviceDlnaPlayInfo];
    } failure:^(NSError *error) {
        NSLog(@"播放-----------------暂停歌曲失败");
        timerSecondCount            =   0;
        isSlow                      =   NO;
        httpDeviceInfoErrorCount ++;
        [self getDeviceDlnaPlayInfo];
    }];
    
    
}


// 拖拽时间进度条进行播放
-(void) seek:(NSTimeInterval) pos {
    NSDictionary *params2           =   [NSDictionary dictionaryWithObjectsAndKeys:[YbrTimerUtil makeClockChooseTimeStr:(int)pos], @"Target", @"REL_TIME", @"Unit", nil];
    
    YbrSetUpBaseReq *setupBaseReq   =   [YbrSetUpBaseReq InitBaseReq:@"PlayerDoSeek" body:params2];
    // 开始网络请求
    NSMutableDictionary *params     =   [NSMutableDictionary dictionary];
    params[@"CMD"]                  =   @"HTTPAPI";
    NSString *req                   =   [YbrJsonUtil getJson:setupBaseReq];
    params[@"JSONREQ"]              =   req;
    
    [IWHttpTool postWithURL:[[YbrDLNAUtil getInstance] getDeviceReqHttpUrl] params:params success:^(id json) {
        timerSecondCount            =   0;
        isSlow                      =   NO;
        if([YbrSetUpWifiBoxUtil isOK:json]) {
            NSLog(@"播放-----------------拖动进度条成功");
        }
        NSLog(@"播放-----------------拖动进度条失败");
        
        [self getDeviceDlnaPlayInfo];
    } failure:^(NSError *error) {
        timerSecondCount            =   0;
        isSlow                      =   NO;
        httpDeviceInfoErrorCount++;
        NSLog(@"播放-----------------拖动进度条失败");
        [self getDeviceDlnaPlayInfo];
    }];
}


// 获得音量(现在这里还访问不到)
// 保留问题
-(float) getVolum {
    return ((float)currVolume) / 100;
}


// 设置音量
-(void) setVolum:(float) value {
    if(value == 1) {
        return;
    }
    NSDictionary *params2           =   [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%i" ,(int)(value * 100)], @"DesiredVolume", nil];
    
    YbrSetUpBaseReq *setupBaseReq   =   [YbrSetUpBaseReq InitBaseReq:@"PlayerSetVolume" body:params2];
    // 开始网络请求
    NSMutableDictionary *params     =   [NSMutableDictionary dictionary];
    params[@"CMD"]                  =   @"HTTPAPI";
    NSString *req                   =   [YbrJsonUtil getJson:setupBaseReq];
    params[@"JSONREQ"]              =   req;
    
    [IWHttpTool postWithURL:[[YbrDLNAUtil getInstance] getDeviceReqHttpUrl] params:params success:^(id json) {
        timerSecondCount            =   0;
        isSlow                      =   NO;
        if([YbrSetUpWifiBoxUtil isOK:json])
        {
            NSLog(@"调整音量成功");
            [[YbrDLNAUtil getInstance] updateDeviceVolume:(int)(value * 100)];
            return;
        }
        NSLog(@"调整音量失败");
    } failure:^(NSError *error) {
        httpDeviceInfoErrorCount ++;
        NSLog(@"调整音量失败");
    }];
}


// 是否有音乐列表
-(BOOL) isHaveMusic {
    if(musiclist == nil || musiclist.count == 0) {
        return NO;
    }
    return YES;
}


// 获取是否是定时
-(BOOL) getIsTime {
    NSLog(@"现在的isTime   %i" ,isTime);
    return isTime;
}


// 获取播放列表的id
-(NSString *) getPlayTimeID {
    return playTimeID;
}


// 在锁屏界面显示歌曲信息
// 这里还有点问题
- (void)showInfoInLockedScreen
{
    NSMutableDictionary *info                   =   [NSMutableDictionary dictionary];
    info[MPMediaItemPropertyTitle]              =   musicItem.musicName;
    info[MPMediaItemPropertyArtist]             =   musicItem.singername == nil ? @"未知歌手" : musicItem.singername;
    info[MPMediaItemPropertyAlbumTitle]         =   musicItem.albumname == nil ? @"未知专辑" : musicItem.albumname;
    info[MPMediaItemPropertyPlaybackDuration]   =   [NSNumber numberWithInt:musicItem.duration];
    
    if([NSString isEmpty:musicItem.img]){
        UIImage *img = [UIImage imageNamed:@"defaultAlbumSmall"];
        info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:img];
    }else{
        NSString *imgurl = [YbrMusicPlayUtil getBitmap];
        
        if(![imgurl hasPrefix:@"http"] && ![imgurl hasSuffix:@"png"]) {
            imgurl = [NSString stringWithFormat:@"%@%@" ,ImgLoad ,imgurl];
        }
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage *img;
            if ([imgurl hasPrefix:@"http"]) {
                img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgurl]]];
            }else{
                img = [YbrSandBox readImage:imgurl];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if (img) {
                    info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:img];
                    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
                }
                
            });
        });
        
    }

    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = info;
}


// 播放状态发生改变了 (暂停,播放,停止)
// 通知全局,播放状态发生改变
-(void) setPlayStateChange {
    [[NSNotificationCenter defaultCenter] postNotificationName:PlayerStateChange object:musicItem];
}



// 播放的项目发生改变 (上下曲 ,播放列表的改变)
-(void) setMetaChange {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithInt:playPos] forKey:@"musicPos"];
    [[NSNotificationCenter defaultCenter] postNotificationName:MetaStateChange object:musicItem];
}



@end
